var app = getApp()
var util = require('../../utils/util.js')
var md5 = require('../md5.js');
Page({
  data: {
    biaodan: {

    }
    
  },
  submit: function () {
    this.setData({
      showModal: true
    })
  },
  onPullDownRefresh: function(){
    wx.stopPullDownRefresh({
      complete: (res) => {},
    });
  },
  //底部导航跳转
  toAiIndex: function () {
    util.toAiIndex()
  },
  toContactsIng: function () {
    util.toContactsIng()
  },
  toProductRevision: function () {
    util.toProductRevision()
  },
  toMy: function () {
    util.toMy()
  },
  toBadge: function () {
    util.toBadge()
  },
  preventTouchMove: function () {

  },
  inputChange(e) {
    var that = this;
    
    var biaodan = that.data.biaodan;
    biaodan[e.currentTarget.dataset.name] = e.detail.value;
    that.setData({
      biaodan: biaodan
    });
    console.log(biaodan)
  },
  upGrmesg: function () {
    var that = this
    console.log('kk=' + that.data.biaodan['lastname'])
    var lastname=''
    var firstname=''
    var position=''
    var company=''
    var mobileno=''
    var email=''
    var address=''
    var website=''
    var postcode=''

    var curlastname = that.data.biaodan['lastname']
    var curfirstname = that.data.biaodan['firstname']
    var curposition = that.data.biaodan['position']
    var curcompany = that.data.biaodan['company']
    var curmobileno = that.data.biaodan['mobileno']
    var curemail = that.data.biaodan['email']
    var curaddress = that.data.biaodan['address']
    var curwebsite = that.data.biaodan['website']
    var curpostcode = that.data.biaodan['postcode']
    
    //定义签名参数
    var curlastnamecs=''
    if (!(!curlastname || curlastname.trim() == "")){
      lastname = curlastname
      curlastnamecs = 'lastname' + lastname
    }
    var curfirstnamecs = ''
    if (!(!curfirstname || curfirstname.trim() == "")) {
      firstname = curfirstname
      curfirstnamecs = 'firstname' + firstname
    }
    var curpositioncs=''
    if (!(!curposition || curposition.trim() == "")) {
      position = curposition
      curpositioncs = 'position' + position
    }
    var curcompanycs=''
    if (!(!curcompany || curcompany.trim() == "")) {
      company = curcompany
      curcompanycs = 'company' + company
    }
    var curmobilenocs=''
    if (!(!curmobileno || curmobileno.trim() == "")) {
      mobileno = curmobileno
      curmobilenocs = 'mobileno' + mobileno
    }
    var curemailcs=''
    if (!(!curemail || curemail.trim() == "")) {
      email = curemail
      curemailcs = 'email' + email
    }
    var curaddresscs=''
    if (!(!curaddress || curaddress.trim() == "")) {
      address = curaddress
      curaddresscs = 'address' + address
    }
    var curwebsitecs = ''
    if (!(!curwebsite || curwebsite.trim() == "")) {
      website = curwebsite
      curwebsitecs = 'website' + website
    }
    var curpostcodecs=''
    if (!(!curpostcode || curpostcode.trim() == "")) {
      postcode = curpostcode
      curpostcodecs = 'postcode' + postcode
    }

    if ((!curlastname || curlastname.trim() == "") || (!curfirstname || curfirstname.trim() == ""))    {
      wx.showToast({
        title: '请填写姓名！',
        icon: 'success',
        duration: 2000
      })
      return
    }else{
      if (!that.checkPhone(curmobileno)) {
        wx.showToast({
          title: '请输入正确手机号！',
          icon: 'success',
          duration: 2000
        })
      } else if (!that.checkEmail(curemail)) {
        wx.showToast({
          title: '请输入正确邮箱！',
          icon: 'success',
          duration: 2000
        })
      }else{
        var exhibitionid = wx.getStorageSync('exhibitionid')
        var u = wx.getStorageSync('u')
        console.log('exhibitionid=' + exhibitionid)
        console.log('u=' + u)
        if ((wx.getStorageSync('exhibitionid') || !"".trim() == wx.getStorageSync('exhibitionid'))
          && (wx.getStorageSync('u') || !"".trim() == wx.getStorageSync('u'))) {
          //默认最新（调用pico接口）
          var timestamp = Date.parse(new Date());
          timestamp = timestamp / 1000;
          var url = app.globalData.picoaddress + '/attendee/user/update'
          var k = {}
          //初始化参数
          if (!(!curlastname || curlastname.trim() == "")) {
            k["lastname"] = curlastname
          }
      
          if (!(!curfirstname || curfirstname.trim() == "")) {
            k["firstname"] = curfirstname
          }
          
          if (!(!curposition || curposition.trim() == "")) {
            k["position"] = curposition
          }

          if (!(!curcompany || curcompany.trim() == "")) {
            k["company"] = curcompany
          }

          if (!(!curmobileno || curmobileno.trim() == "")) {
            k["mobileno"] = curmobileno
          }
          
          if (!(!curemail || curemail.trim() == "")) {
            k["email"] = curemail
          }
          
          if (!(!curaddress || curaddress.trim() == "")) {
            k["address"] = curaddress
          }
   
          if (!(!curwebsite || curwebsite.trim() == "")) {
            k["website"] = curwebsite
          }
          
          if (!(!curpostcode || curpostcode.trim() == "")) {
            k["postcode"] = curpostcode
          }

          k["v"] = '1.0.0'
          k["client"] = 'ios'
          k["timestamp"] = timestamp
          k["lan"] = 'cn'
          k["exhibitionid"] = exhibitionid
          k["u"] = u

          var sign = app.globalData.picotoken + curaddresscs + 'clientios' + curcompanycs + curemailcs + 'exhibitionid' + exhibitionid + curfirstnamecs + curlastnamecs + curmobilenocs + curpositioncs + curpostcodecs + 'timestamp' + timestamp + curwebsitecs + app.globalData.picotoken
          console.log('sign='+sign)
        
          var curb64 = md5.zhMD5(sign)
          console.log(curb64)
          k["sign"] = curb64
          wx.request({
            header: {
              'content-type': 'application/x-www-form-urlencoded',
            },
            url: url,
            method: 'post',
            data: k,
            success(res) {
              console.log(res)
              wx.showToast({
                title: '修改成功！',
                icon: 'success',
                duration: 2000
              })
              wx.navigateTo({
                url: '../my/my',
              })
            }, fail: res => {
              console.log(res, "error")
            }

          })

        } else {
          wx.redirectTo({
            url: '../signInbyPhone/signIn'
          })
        }

      }

    }
  },
  go: function () {
    this.setData({
      showModal: false
    })
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    var that = this;
    //设置语言0:中文，1：英文
    var setlanguage = wx.getStorageSync('setlanguage')
    if ((wx.getStorageSync('setlanguage') || !"".trim() == wx.getStorageSync('setlanguage'))) {
      this.setData({
        setlanguage: wx.getStorageSync('setlanguage')
      })
      if (setlanguage == 1) {
        wx.setNavigationBarTitle({
          title: 'Personal Center'
        })
      } else {
        wx.setNavigationBarTitle({
          title: '个人中心'
        })
      }
    } else {
      wx.setStorageSync('setlanguage', 0);
      this.setData({
        setlanguage: 0
      })
    }
    var exhibitionid = wx.getStorageSync('exhibitionid')
    var u = wx.getStorageSync('u')
    console.log('exhibitionid=' + exhibitionid)
    console.log('u=' + u)
    if ((wx.getStorageSync('exhibitionid') || !"".trim() == wx.getStorageSync('exhibitionid'))
      && (wx.getStorageSync('u') || !"".trim() == wx.getStorageSync('u'))) {
      //默认最新（调用pico接口）
      var timestamp = Date.parse(new Date());
      timestamp = timestamp / 1000;
      var url = app.globalData.picoaddress + '/attendee/user/profile'
      var k = {}
      k["v"] = '1.0.0'
      k["client"] = 'ios'
      k["timestamp"] = timestamp
      k["lan"] = 'cn'
      k["exhibitionid"] = exhibitionid
      k["u"] = u

      var sign = app.globalData.picotoken + 'clientiosexhibitionid' + exhibitionid + 'timestamp' + timestamp + app.globalData.picotoken
      console.log(sign)
      var curb64 = md5.hexMD5(sign)
      console.log(curb64)
      k["sign"] = curb64
      wx.request({
        header: {
          'content-type': 'application/x-www-form-urlencoded',
        },
        url: url,
        method: 'post',
        data: k,
        success(res) {
          console.log(res)
          var mesg = res.data
          console.log('mesg=' + mesg)
          var curdata = mesg.data
          console.log('curdata=', curdata)
          var biaodan = that.data.biaodan;
          biaodan['lastname'] = curdata.lastname
          biaodan["firstname"] = curdata.firstname
          biaodan["position"] = curdata.position
          biaodan["company"] = curdata.company
          biaodan["mobileno"] = curdata.mobileno
          biaodan["email"] = curdata.email
          biaodan["address"] = curdata.address
          biaodan["website"] = curdata.website
          biaodan["postcode"] = curdata.postcode
          that.setData({
            perMesg: curdata,
            biaodan: biaodan 
          });
        }, fail: res => {
          console.log(res, "error")
        }

      })
      //获取头像
      var url1 = app.globalData.picoaddress + '/Attendee/user/getdeviceid'
      wx.request({
        header: {
          'content-type': 'application/x-www-form-urlencoded',
        },
        url: url1,
        method: 'post',
        data: k,
        success(res) {
          console.log(res)
          var mesg = res.data
          console.log('mesg=' + mesg)
          var curdata = mesg.data
          that.setData({
            grMesg: curdata
          });
        }, fail: res => {
          console.log(res, "error")
        }

      })

    } else {
      wx.redirectTo({
        url: '../signInbyPhone/signIn'
      })
    }
  }, 
  uploadPhoto(e) { // 拍摄或从相册选取上传
    let that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        console.log("base64=" + wx.getFileSystemManager().readFileSync(res.tempFilePaths[0], "base64"))
        var base64img = wx.getFileSystemManager().readFileSync(res.tempFilePaths[0], "base64") + ''
        //上传头像
        var exhibitionid = wx.getStorageSync('exhibitionid')
        var u = wx.getStorageSync('u')
        if ((wx.getStorageSync('exhibitionid') || !"".trim() == wx.getStorageSync('exhibitionid'))
          && (wx.getStorageSync('u') || !"".trim() == wx.getStorageSync('u'))) {
          //默认最新（调用pico接口）
          var timestamp = Date.parse(new Date());
          timestamp = timestamp / 1000;
          var url = app.globalData.picoaddress + '/attendee/user/uploadphoto'
          var k = {}
          k["v"] = '1.0.0'
          k["client"] = 'ios'
          k["timestamp"] = timestamp
          k["lan"] = 'cn'
          k["exhibitionid"] = exhibitionid
          k["u"] = u
          k["base64img"] = base64img
          var sign = app.globalData.picotoken + 'clientiosexhibitionid' + exhibitionid + 'timestamp' + timestamp + app.globalData.picotoken
          console.log(sign)
          var curb64 = md5.hexMD5(sign)
          console.log(curb64)
          k["sign"] = curb64
          wx.request({
            header: {
              'content-type': 'application/x-www-form-urlencoded',
            },
            url: url,
            method: 'post',
            data: k,
            success(res) {
              wx.showToast({
                title: '更新头像中',
                icon: 'none',
                duration: 2000
              })
              var exhibitionid = wx.getStorageSync('exhibitionid')
              var u = wx.getStorageSync('u')
              console.log('exhibitionid=' + exhibitionid)
              console.log('u=' + u)
              if ((wx.getStorageSync('exhibitionid') || !"".trim() == wx.getStorageSync('exhibitionid'))
                && (wx.getStorageSync('u') || !"".trim() == wx.getStorageSync('u'))) {
                //默认最新（调用pico接口）
                var timestamp = Date.parse(new Date());
                timestamp = timestamp / 1000;
                var url = app.globalData.picoaddress + '/attendee/user/profile'
                var k = {}
                k["v"] = '1.0.0'
                k["client"] = 'ios'
                k["timestamp"] = timestamp
                k["lan"] = 'cn'
                k["exhibitionid"] = exhibitionid
                k["u"] = u

                var sign = app.globalData.picotoken + 'clientiosexhibitionid' + exhibitionid + 'timestamp' + timestamp + app.globalData.picotoken
                console.log(sign)
                var curb64 = md5.hexMD5(sign)
                console.log(curb64)
                k["sign"] = curb64
                wx.request({
                  header: {
                    'content-type': 'application/x-www-form-urlencoded',
                  },
                  url: url,
                  method: 'post',
                  data: k,
                  success(res) {
                    console.log(res)
                    var mesg = res.data
                    console.log('mesg=' + mesg)
                    var curdata = mesg.data
                    console.log('curdata=', curdata)
                    var biaodan = that.data.biaodan;
                    biaodan['lastname'] = curdata.lastname
                    biaodan["firstname"] = curdata.firstname
                    biaodan["position"] = curdata.position
                    biaodan["company"] = curdata.company
                    biaodan["mobileno"] = curdata.mobileno
                    biaodan["email"] = curdata.email
                    biaodan["address"] = curdata.address
                    biaodan["website"] = curdata.website
                    biaodan["postcode"] = curdata.postcode
                    that.setData({
                      perMesg: curdata,
                      biaodan: biaodan
                    });
                  }, fail: res => {
                    console.log(res, "error")
                  }

                })
                //获取头像
                var url1 = app.globalData.picoaddress + '/Attendee/user/getdeviceid'
                wx.request({
                  header: {
                    'content-type': 'application/x-www-form-urlencoded',
                  },
                  url: url1,
                  method: 'post',
                  data: k,
                  success(res) {
                    console.log(res)
                    var mesg = res.data
                    console.log('mesg=' + mesg)
                    var curdata = mesg.data
                    that.setData({
                      grMesg: curdata
                    });
                  }, fail: res => {
                    console.log(res, "error")
                  }

                })

              }
            }, fail: res => {
              console.log(res, "error")
            }
          })
        }


      },
    })

  },
  checkEmail(num) {//检查邮箱是否合法 
    if (!(/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/.test(num))) {
      // console.log("邮箱有误，请重填");
      return false;
    }
    return true;
  },
  checkPhone(phone) {//检查手机号是否合法 
    if (!(/^1[34578]\d{9}$/.test(phone))) {
      // console.log("手机号码有误，请重填");
      return false;
    }
    return true;
  },
  edit:function () {
    
    wx.chooseImage({
      count:1,
      complete: (res) => {
        var filePath = res.tempFilePaths[0];
        this.setData({
          filePath : filePath,
        });

      },
    })
  },
})